import { PageObj, Response } from '@/typings/api'
import { Select, SelectProps } from 'antd';
import { AnyObject } from 'antd/es/_util/type';
import { useCallback, useEffect, useState } from 'react'
import lodash from 'lodash';

interface ListApiParam extends AnyObject {
    page: number; pageSize: number
}

interface SearchSelectProps extends SelectProps {
    listApi: (options: ListApiParam) => Promise<Response<PageObj>>
    searchKey: string;
}
const SearchSelect = ({ value, onChange, searchKey, listApi, ...props }: SearchSelectProps) => {
    const [options, setOptions] = useState<any[]>([]);
    const fetchOptions = async (keywords?: string) => {
        const params: ListApiParam = { page: 1, pageSize: 10 };
        if (keywords) params[searchKey] = keywords;
        // prettier-ignore
        const { data: { list } } = await listApi(params);
        setOptions(list);
    };
    const handleSearch = useCallback(lodash.debounce(fetchOptions, 300), []);
    useEffect(() => {
        fetchOptions();
    }, []);
    const [innerValue, setInnerValue] = useState<string[]>([]);
    useEffect(() => {
        setInnerValue(value || []);
    }, [value]);
    return (
        <Select
            {...props}
            value={innerValue}
            showSearch
            onSearch={handleSearch}
            onChange={(val, option) => {
                setInnerValue(val);
                onChange?.(val, option);
            }}
            options={options.map(item => ({ label: item[searchKey], value: item._id }))}
            filterOption={false}
        />
    );
}

export default SearchSelect